package controllers

import (
	"fuxi/models"
	beego "github.com/beego/beego/v2/server/web"
	"io"
	os "os"
	"path/filepath"
)

type XinwenController struct {
	beego.Controller
}

func (c *XinwenController) Unload() {
	file, m, _ := c.GetFile("img")
	ext := filepath.Ext(m.Filename)
	if ext != ".png" && ext != ".jpg" && ext != ".jpeg" {
		res := Msg{
			Code: 0,
			Msg:  "格式不是。jpg.jpeg.png",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	if m.Size > 201027*1024 {
		res := Msg{
			Code: 0,
			Msg:  "不能超过2MB",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	openFile, _ := os.OpenFile("static/img/"+m.Filename, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0777)
	io.Copy(openFile, file)
	res := Msg{
		Code: 200,
		Msg:  "文件上传成功",
		Data: "http://127.0.0.1:8080/static/img/" + m.Filename,
	}
	c.Data["json"] = res
	c.ServeJSON()
}
func (c *XinwenController) Add() {
	name := c.GetString("name")
	img := c.GetString("img")
	ss := models.Xinwen{
		Name: name,
		Img:  img,
	}
	err := models.DB.Debug().Create(&ss).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "添加失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "添加成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *XinwenController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	i := (page - 1) * size
	var alloct []models.Xinwen
	err := models.DB.Debug().Offset(i).Limit(size).Find(&alloct).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "展示失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "展示成功",
			Data: alloct,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *XinwenController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.Xinwen{}, id).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "删除失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "删除成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
